# -*- coding: utf-8 -*-
# -------------------------------
# @文件：get_allure_data.py
# @时间：2024/4/9 下午4:18
# @作者：caiweichao
# @功能描述：获取 allure 测试报告中的用例数据
# -------------------------------
import json
import os

from config.constants_path import REPORT_PATH


class AllureFileClean:
    """allure 报告数据清洗，提取业务需要得数据"""

    @classmethod
    def _getAllFiles(cls) -> list:
        """ 获取所有 test-case 中的 json 文件 """
        filename = []
        # 获取所有文件下的子文件名称
        for root, dirs, files in os.walk(REPORT_PATH + '/data/test-cases'):
            for filePath in files:
                path = os.path.join(root, filePath)
                filename.append(path)
        return filename

    def get_testcases(self):
        """ 获取所有 allure 报告中执行用例的情况"""
        # 将所有数据都收集到files中
        files = []
        for i in self._getAllFiles():
            with open(i, 'r', encoding='utf-8') as fp:
                date = json.load(fp)
                files.append(date)
        return files

    def get_failed_case(self):
        """ 获取到所有失败的用例标题和用例代码路径"""
        errorCase = []
        for i in self.get_testcases():
            if i['status'] == 'failed' or i['status'] == 'broken':
                errorCase.append((i['name'], i['fullName']))
        return errorCase

    def get_failed_cases_detail(self):
        """ 返回所有失败的测试用例相关内容 """
        Data = self.get_failed_case()
        # 判断有失败用例，则返回内容
        if len(Data) >= 1:
            values = ""
            for i in Data:
                values += i[0] + ","
            return values
        else:
            # 如果没有失败用例，则返回False
            return ""

    @classmethod
    def get_case_count(cls):
        """ 统计用例数量 """
        fileName = REPORT_PATH + '/history/history-trend.json'
        with open(fileName, 'r', encoding='utf-8') as fp:
            date = json.load(fp)[0]['data']
        return date


class CaseCount:
    def __init__(self):
        self.AllureData = AllureFileClean()
        self.total_cases = self.AllureData.get_case_count()['total']
        self.pass_case = self.AllureData.get_case_count()['passed']
        self.fail_case = self.AllureData.get_case_count()['failed']
        self.broken_case = self.AllureData.get_case_count()['broken']
        self.skipped_case = self.AllureData.get_case_count()['skipped']

    def passRate(self):
        """用例成功率"""
        # 四舍五入，保留2位小数
        try:
            if self.total_cases() != 0:
                passRate = round(self.pass_case() / (self.total_cases() - self.skipped_case()) * 100, 2)
            else:
                passRate = round(self.pass_case() / self.total_cases() * 100, 2)
            return passRate
        except ZeroDivisionError:
            return 0.00
